#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于事件系统的消息统计插件
"""

import json
import os
from datetime import datetime, timedelta
from typing import Dict, Optional, Any
from common.logger import logger
from plugins.base_plugin import BasePlugin
from plugins.event_system import Event, EventType, on_message, on_any_message, middleware


class Plugin(BasePlugin):
    """基于事件系统的消息统计插件类"""
    
    def __init__(self, config: Dict[str, Any], event_bus):
        super().__init__(config, event_bus)
        self.stats_file = "data/message_stats.json"
        self.message_count = 0
        self.message_type_stats = {}
        self.user_stats = {}
        self.group_stats = {}
        self.last_save_time = datetime.now()
        self.auto_save_interval = self.settings.get("auto_save_interval", 300)  # 5分钟
        self.max_history_days = self.settings.get("max_history_days", 7)
        
        # 确保数据目录存在
        os.makedirs("data", exist_ok=True)
        
        # 加载历史统计数据
        self._load_stats()
    
    def _load_stats(self):
        """加载统计数据"""
        try:
            if os.path.exists(self.stats_file):
                with open(self.stats_file, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    self.message_count = data.get("message_count", 0)
                    self.message_type_stats = data.get("message_type_stats", {})
                    self.user_stats = data.get("user_stats", {})
                    self.group_stats = data.get("group_stats", {})
                    logger.info(f"加载统计数据: 总消息数 {self.message_count}")
        except Exception as e:
            logger.error(f"加载统计数据失败: {e}")
    
    def _save_stats(self):
        """保存统计数据"""
        try:
            data = {
                "message_count": self.message_count,
                "message_type_stats": self.message_type_stats,
                "user_stats": self.user_stats,
                "group_stats": self.group_stats,
                "last_update": datetime.now().isoformat()
            }
            
            with open(self.stats_file, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            logger.debug("统计数据已保存")
        except Exception as e:
            logger.error(f"保存统计数据失败: {e}")
    
    def _cleanup_old_stats(self):
        """清理旧统计数据"""
        try:
            cutoff_date = datetime.now() - timedelta(days=self.max_history_days)
            cutoff_str = cutoff_date.isoformat()
            
            # 清理用户统计
            for user_id in list(self.user_stats.keys()):
                if self.user_stats[user_id].get("last_message", "") < cutoff_str:
                    del self.user_stats[user_id]
            
            # 清理群组统计
            for group_id in list(self.group_stats.keys()):
                if self.group_stats[group_id].get("last_message", "") < cutoff_str:
                    del self.group_stats[group_id]
                    
        except Exception as e:
            logger.error(f"清理旧统计数据失败: {e}")
    
    @middleware()
    async def count_messages(self, event: Event):
        """统计消息数量的中间件"""
        try:
            if not self.is_enabled():
                return
            
            data = event.data
            msg_type = data.get("msg_type", 0)
            sender_wxid = data.get("sender_wxid", "")
            from_wxid = data.get("from_wxid", "")
            is_group = data.get("is_group", False)
            
            # 更新总消息数
            self.message_count += 1
            
            # 更新消息类型统计
            msg_type_str = str(msg_type)
            if msg_type_str not in self.message_type_stats:
                self.message_type_stats[msg_type_str] = 0
            self.message_type_stats[msg_type_str] += 1
            
            # 更新用户统计
            if sender_wxid:
                if sender_wxid not in self.user_stats:
                    self.user_stats[sender_wxid] = {
                        "message_count": 0,
                        "last_message": "",
                        "message_types": {}
                    }
                self.user_stats[sender_wxid]["message_count"] += 1
                self.user_stats[sender_wxid]["last_message"] = datetime.now().isoformat()
                
                if msg_type_str not in self.user_stats[sender_wxid]["message_types"]:
                    self.user_stats[sender_wxid]["message_types"][msg_type_str] = 0
                self.user_stats[sender_wxid]["message_types"][msg_type_str] += 1
            
            # 更新群组统计
            if is_group and from_wxid:
                if from_wxid not in self.group_stats:
                    self.group_stats[from_wxid] = {
                        "message_count": 0,
                        "last_message": "",
                        "message_types": {}
                    }
                self.group_stats[from_wxid]["message_count"] += 1
                self.group_stats[from_wxid]["last_message"] = datetime.now().isoformat()
                
                if msg_type_str not in self.group_stats[from_wxid]["message_types"]:
                    self.group_stats[from_wxid]["message_types"][msg_type_str] = 0
                self.group_stats[from_wxid]["message_types"][msg_type_str] += 1
            
            # 定期保存和清理
            if (datetime.now() - self.last_save_time).seconds >= self.auto_save_interval:
                self._save_stats()
                self._cleanup_old_stats()
                self.last_save_time = datetime.now()
                
        except Exception as e:
            logger.error(f"统计消息失败: {e}")
    
    @on_message(EventType.MESSAGE_TEXT)
    async def handle_text_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理文本消息事件"""
        try:
            if not self.is_enabled():
                return None
            
            data = event.data
            content = data.get("content", "")
            sender_wxid = data.get("sender_wxid", "")
            
            # 处理统计命令
            if content == "统计":
                return self._get_stats_response()
            elif content == "重置统计":
                return self._reset_stats_response()
            
            return None
            
        except Exception as e:
            logger.error(f"统计插件处理文本消息失败: {e}")
            return None
    
    @on_any_message()
    async def handle_any_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理任意消息事件（用于调试）"""
        try:
            if not self.is_enabled():
                return None
            
            data = event.data
            msg_type = data.get("msg_type", 0)
            sender_wxid = data.get("sender_wxid", "")
            
            # 每1000条消息输出一次统计信息
            if self.message_count % 1000 == 0:
                logger.info(f"消息统计: 总数 {self.message_count}, 类型 {msg_type}, 用户 {sender_wxid}")
            
        except Exception as e:
            logger.error(f"统计插件处理任意消息失败: {e}")
        
        return None
    
    def _get_stats_response(self) -> Dict[str, Any]:
        """获取统计信息响应"""
        try:
            # 获取消息类型名称
            type_names = {
                "1": "文本消息",
                "3": "图片消息",
                "34": "语音消息",
                "43": "视频消息",
                "47": "动画表情",
                "49": "多媒体消息"
            }
            
            # 构建统计信息
            stats_text = f"📊 消息统计信息\n\n"
            stats_text += f"📈 总消息数: {self.message_count}\n\n"
            
            # 消息类型统计
            stats_text += "📋 消息类型统计:\n"
            for msg_type, count in sorted(self.message_type_stats.items(), key=lambda x: x[1], reverse=True):
                type_name = type_names.get(msg_type, f"类型{msg_type}")
                stats_text += f"  {type_name}: {count}条\n"
            
            # 用户统计（前5名）
            if self.user_stats:
                stats_text += f"\n👥 活跃用户统计 (前5名):\n"
                sorted_users = sorted(self.user_stats.items(), key=lambda x: x[1]["message_count"], reverse=True)[:5]
                for i, (user_id, user_data) in enumerate(sorted_users, 1):
                    stats_text += f"  {i}. {user_id}: {user_data['message_count']}条\n"
            
            # 群组统计（前3名）
            if self.group_stats:
                stats_text += f"\n👥 活跃群组统计 (前3名):\n"
                sorted_groups = sorted(self.group_stats.items(), key=lambda x: x[1]["message_count"], reverse=True)[:3]
                for i, (group_id, group_data) in enumerate(sorted_groups, 1):
                    stats_text += f"  {i}. {group_id}: {group_data['message_count']}条\n"
            
            return self.create_text_response(stats_text)
            
        except Exception as e:
            logger.error(f"生成统计响应失败: {e}")
            return self.create_text_response("获取统计信息失败")
    
    def _reset_stats_response(self) -> Dict[str, Any]:
        """重置统计响应"""
        try:
            # 重置统计数据
            self.message_count = 0
            self.message_type_stats.clear()
            self.user_stats.clear()
            self.group_stats.clear()
            
            # 保存重置后的数据
            self._save_stats()
            
            logger.info("统计数据已重置")
            return self.create_text_response("✅ 统计数据已重置")
            
        except Exception as e:
            logger.error(f"重置统计数据失败: {e}")
            return self.create_text_response("❌ 重置统计数据失败")
    
    async def on_unload(self):
        """插件卸载时保存统计数据"""
        try:
            self._save_stats()
            logger.info("统计插件卸载，数据已保存")
        except Exception as e:
            logger.error(f"保存统计数据失败: {e}") 